﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Code.Models;
using System.Security.Cryptography;
using System.Data.SqlClient;
using Code.DAL;

namespace Code.BLL
{
    public class SiteManage : ManageBase<Option_Site>
    {
        /// <summary>
        /// 修改Key所对应的Option，没有时则添加一条
        /// </summary>
        /// <param name="key">Option的Key</param>
        /// <param name="value">Option的Value</param>
        /// <returns></returns>
        public int Update(string key, string value)
        {
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException("key");
            if (string.IsNullOrEmpty(value))
                throw new ArgumentNullException("value");

            int rs = -1;
            var flag = base.Select(s => s.Select(p => p.Key.ToString()).Contains(key));
            if (flag)
                rs = base.Update(new { value }, new { key });
            else
                rs = base.Insert(new { key, value });

            return rs;
        }

        public int ClearData(DateTime date, string pwd)
        {
            int rs = -1;
            string str = System.Configuration.ConfigurationManager.AppSettings["ClearDataMaxDay"];
            int day = int.TryParse(str, out day) ? day + 1 : 3;
            if (date.Date.AddDays(day) > DateTime.Now.Date)
                throw new ValidateException("只能清除至" + DateTime.Now.Date.AddDays(0 - day).ToShortDateString(), "date");
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");
            var result = base.Tables.ClearData(date.Date).Single();
            if (result.Result.HasValue && result.Result.Value)
                rs = result.RowCount.Value;

            return rs;
        }

        public int LoginLogClear(DateTime date, string pwd)
        {
            int rs = -1;
            string str = System.Configuration.ConfigurationManager.AppSettings["ClearDataMaxDay"];
            int day = int.TryParse(str, out day) ? day + 1 : 3;
            if (date.Date.AddDays(day) > DateTime.Now.Date)
                throw new ValidateException("只能清除至" + DateTime.Now.Date.AddDays(0 - day).ToShortDateString(), "date");
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");
            rs = base.Delete<LoginLog>(new { LoginTime = new ComparValue(Comparison.LessThanOrEqual, date) });

            return rs;
        }

        public int YeePayOption(bool enable, string memberid, string key, string addr, string pwd)
        {
            int rs = -1;

            if (enable)
            {
                if (string.IsNullOrEmpty(memberid))
                    throw new ValidateException("启用状态不能为空", "memeberid");
                if (string.IsNullOrEmpty(key))
                    throw new ValidateException("启用状态不能为空", "kdy");
                if (string.IsNullOrEmpty(addr))
                    throw new ValidateException("启用状态不能为空", "addr");
            }
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");
            string[] items = new string[] { 
                Option_Site_Key.Site_Pay_YeePay_Enable.ToString(), 
                Option_Site_Key.Site_Pay_YeePay_MerhantID.ToString(),
                Option_Site_Key.Site_Pay_YeePay_Key.ToString(),
                Option_Site_Key.Site_Pay_YeePay_ReqUrl.ToString()
            };
            string[] values = new string[]
            {
                enable.ToString(),
                memberid,
                key,
                addr,
            };

            base.BeginTransaction();
            var ups = base.Select(s => s.Where(p => items.Contains(p.Key))).ToArray();
            items.Each((p, i) =>
            {
                var c = ups.FirstOrDefault(pp => pp.Key == items[i]);
                if (c != null && c.Value != values[i])
                    base.Update(new { Value = values[i] }, new { Key = items[i] });
                else if (c == null)
                    base.Insert(new { Value = values[i], Key = items[i] });
            });
            rs = base.ExecuteTransaction();
            return rs;
        }
        public int AliPayOption(bool enable, string memberid, string key, string addr, string pwd, string email, string membername)
        {
            int rs = -1;

            if (enable)
            {
                if (string.IsNullOrEmpty(memberid))
                    throw new ValidateException("启用状态不能为空", "memeberid");
                if (string.IsNullOrEmpty(key))
                    throw new ValidateException("启用状态不能为空", "kdy");
                if (string.IsNullOrEmpty(addr))
                    throw new ValidateException("启用状态不能为空", "addr");
                if (string.IsNullOrEmpty(email))
                    throw new ValidateException("启用状态不能为空", "email");
            }
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");
            string[] items = new string[] { 
                Option_Site_Key.Site_Pay_AliPay_Enable.ToString(), 
                Option_Site_Key.Site_Pay_AliPay_MerhantID.ToString(),
                Option_Site_Key.Site_Pay_AliPay_Key.ToString(),
                Option_Site_Key.Site_Pay_AliPay_ReqUrl.ToString(),
                Option_Site_Key.Site_Pay_AliPay_Email.ToString(),
            };
            string[] values = new string[]
            {
                enable.ToString(),
                memberid,
                key,
                addr,
                email,
                membername,
            };

            base.BeginTransaction();
            var ups = base.Select(s => s.Where(p => items.Contains(p.Key))).ToArray();
            items.Each((p, i) =>
            {
                var c = ups.FirstOrDefault(pp => pp.Key == items[i]);
                if (c != null && c.Value != values[i])
                    base.Update(new { Value = values[i] }, new { Key = items[i] });
                else if (c == null)
                    base.Insert(new { Value = values[i], Key = items[i] });
            });
            rs = base.ExecuteTransaction();
            return rs;
        }
        public int TenPayOption(bool enable, string memberid, string key, string addr, string pwd, string membername)
        {
            int rs = -1;

            if (enable)
            {
                if (string.IsNullOrEmpty(memberid))
                    throw new ValidateException("启用状态不能为空", "memeberid");
                if (string.IsNullOrEmpty(key))
                    throw new ValidateException("启用状态不能为空", "kdy");
                if (string.IsNullOrEmpty(addr))
                    throw new ValidateException("启用状态不能为空", "addr");
            }
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");
            string[] items = new string[] { 
                Option_Site_Key.Site_Pay_TenPay_Enable.ToString(),
                Option_Site_Key.Site_Pay_TenPay_MerhantID.ToString(),
                Option_Site_Key.Site_Pay_TenPay_Key.ToString(),
                Option_Site_Key.Site_Pay_TenPay_ReqUrl.ToString()
            };
            string[] values = new string[]
            {
                enable.ToString(),
                memberid,
                key,
                addr,
                membername,
            };

            base.BeginTransaction();
            var ups = base.Select(s => s.Where(p => items.Contains(p.Key))).ToArray();
            items.Each((p, i) =>
            {
                var c = ups.FirstOrDefault(pp => pp.Key == items[i]);
                if (c != null && c.Value != values[i])
                    base.Update(new { Value = values[i] }, new { Key = items[i] });
                else if (c == null)
                    base.Insert(new { Value = values[i], Key = items[i] });
            });
            rs = base.ExecuteTransaction();
            return rs;
        }
        #region 工行
        public int ICBC_ManualOption(bool enable, string membername, string memberid, string memo, string pwd, double? chargeragio, double? mincharge, double? maxcharge)
        {
            int rs = -1;
            List<string> items = new List<string>();
            items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_Enable.ToString());
            items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_Memo.ToString());
            items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_ChargeRatio.ToString());
            items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_MinCharge.ToString());
            items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_MaxCharge.ToString());
            List<string> values = new List<string>();
            values.Add(enable.ToString());
            values.Add(memo);
            values.Add(chargeragio.ToString());
            values.Add(mincharge.ToString());
            values.Add(maxcharge.ToString());
            if (enable)
            {
                if (mincharge.HasValue && maxcharge.HasValue && maxcharge < mincharge)
                    throw new ValidateException("大于最小手续费", "maxcharge");
                items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_MemberID.ToString());
                items.Add(Option_Site_Key.Site_Pay_ICBC_Manual_MemberName.ToString());
                values.Add(memberid);
                values.Add(membername);
              
                
            }
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");

            base.BeginTransaction();
            var ups = base.Select(s => s.Where(p => items.Contains(p.Key))).ToArray();
            items.Each((p, i) =>
            {
                var c = ups.FirstOrDefault(pp => pp.Key == items[i]);
                if (c != null && c.Value != values[i])
                    base.Update(new { Value = values[i] }, new { Key = items[i] });
                else if (c == null)
                    base.Insert(new { Value = values[i], Key = items[i] });
            });
            rs = base.ExecuteTransaction();
            return rs;
        }
        #endregion

        #region 支付宝人工转账
        public int Alipas_ManualOption(bool enable, string membername, string memberid, string memo, string pwd, double? chargeragio, double? mincharge, double? maxcharge)
        {


            int rs = -1;
            List<string> items = new List<string>();
            items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_Enable.ToString());
            items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_Memo.ToString());
            items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_ChargeRatio.ToString());
            items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_MinCharge.ToString());
            items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_MaxCharge.ToString());
            List<string> values = new List<string>();
            values.Add(enable.ToString());
            values.Add(memo);
            values.Add(chargeragio.ToString());
            values.Add(mincharge.ToString());
            values.Add(maxcharge.ToString());
            if (enable)
            {
                if (mincharge.HasValue && maxcharge.HasValue && maxcharge < mincharge)
                    throw new ValidateException("大于最小手续费", "maxcharge");
                items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_MemberID.ToString());
                items.Add(Option_Site_Key.Site_Pay_Alipays_Manual_MemberName.ToString());
                values.Add(memberid);
                values.Add(membername);


            }
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");

            base.BeginTransaction();
            var ups = base.Select(s => s.Where(p => items.Contains(p.Key))).ToArray();
            items.Each((p, i) =>
            {
                var c = ups.FirstOrDefault(pp => pp.Key == items[i]);
                if (c != null && c.Value != values[i])
                    base.Update(new { Value = values[i] }, new { Key = items[i] });
                else if (c == null)
                    base.Insert(new { Value = values[i], Key = items[i] });
            });
            rs = base.ExecuteTransaction();
            return rs; 
        }
        #endregion

        #region 财付通人工转账
        public int TenPay_ManualOption(bool enable, string membername, string memberid, string memo, string pwd, double? chargeragio, double? mincharge, double? maxcharge)
        {
            int rs = -1;
            List<string> items = new List<string>();
            items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_Enable.ToString());
            items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_Memo.ToString());
            items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_ChargeRatio.ToString());
            items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_MinCharge.ToString());
            items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_MaxCharge.ToString());
            List<string> values = new List<string>();
            values.Add(enable.ToString());
            values.Add(memo);
            values.Add(chargeragio.ToString());
            values.Add(mincharge.ToString());
            values.Add(maxcharge.ToString());
            if (enable)
            {
                if (mincharge.HasValue && maxcharge.HasValue && maxcharge < mincharge)
                    throw new ValidateException("大于最小手续费", "maxcharge");
                items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_MemberID.ToString());
                items.Add(Option_Site_Key.Site_Pay_TenPays_Manual_MemberName.ToString());
                values.Add(memberid);
                values.Add(membername);
            }
            MD5 md5 = MD5.Create();
            pwd = md5.ComputeHash(pwd, Salt.Password.GetMd5Salt());
            if (pwd != CacheManage.OptionSite[Option_Site_Key.Site_Other_ClearDataPwd].Value)
                throw new ValidateException("密码不正确", "pwd");

            base.BeginTransaction();
            var ups = base.Select(s => s.Where(p => items.Contains(p.Key))).ToArray();
            items.Each((p, i) =>
            {
                var c = ups.FirstOrDefault(pp => pp.Key == items[i]);
                if (c != null && c.Value != values[i])
                    base.Update(new { Value = values[i] }, new { Key = items[i] });
                else if (c == null)
                    base.Insert(new { Value = values[i], Key = items[i] });
            });
            rs = base.ExecuteTransaction();
            return rs;
        }
        #endregion
        public bool IsRegest(string name)
        {
            var str = MD5.Create().ComputeHash(name, Salt.Keys.GetMd5Salt());
            return (base.Select(s => s.Where(p => p.Key == "Site_RegestCode").Select(p => p.Value).FirstOrDefault()) ?? "").Contains(str);
        }
        /// <summary>
        /// 获取不同奖金模式的返点
        /// </summary>
        /// <returns></returns>
        public List<BackMoneyRatioModel> GetBackMoneyRatios()
        {
            var list = new List<BackMoneyRatioModel>();
            var minBackMoneyMarginRatio = base.Select(s => s.FirstOrDefault(p => p.Key == Option_Site_Key.Site_Lottery_MinBackMoneyMarginRatio.ToString())).Value;
            var maxBackMoneyRatio = base.Select(s => s.FirstOrDefault(p => p.Key == Option_Site_Key.Site_Lottery_MaxBackMoneyMarginRatio.ToString())).Value;
            var member_MaxBackMoneyRatio = base.Select(s => s.FirstOrDefault(p => p.Key == Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio.ToString())).Value;
            var minBackMoneyRatio = base.Select(s => s.FirstOrDefault(p => p.Key == Option_Site_Key.Site_Lottery_MinBackMoneyRatio.ToString())).Value;
            CacheManage.WinModel.Each(p =>
            {
                var bmrm = new BackMoneyRatioModel();
                bmrm.key = Option_Site_Key.Site_Lottery_MinBackMoneyMarginRatio;
                bmrm.WinModelID = p.Value.ID;
                bmrm.Value = string.IsNullOrEmpty(minBackMoneyMarginRatio) ? "" : (minBackMoneyMarginRatio.Split(',').FirstOrDefault(pp => pp.StartsWith(p.Value.ID.ToString())) ?? "_").Split('_')[1];
                list.Add(bmrm);
                bmrm = new BackMoneyRatioModel();
                bmrm.key = Option_Site_Key.Site_Lottery_MaxBackMoneyMarginRatio;
                bmrm.WinModelID = p.Value.ID;
                bmrm.Value = string.IsNullOrEmpty(maxBackMoneyRatio) ? "" : (maxBackMoneyRatio.Split(',').FirstOrDefault(pp => pp.StartsWith(p.Value.ID.ToString())) ?? "_").Split('_')[1];
                list.Add(bmrm);
                bmrm = new BackMoneyRatioModel();
                bmrm.key = Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio;
                bmrm.WinModelID = p.Value.ID;
                bmrm.Value = string.IsNullOrEmpty(member_MaxBackMoneyRatio) ? "" : (member_MaxBackMoneyRatio.Split(',').FirstOrDefault(pp => pp.StartsWith(p.Value.ID.ToString())) ?? "_").Split('_')[1];
                list.Add(bmrm);
                bmrm = new BackMoneyRatioModel();
                bmrm.key = Option_Site_Key.Site_Lottery_MinBackMoneyRatio;
                bmrm.WinModelID = p.Value.ID;
                bmrm.Value = string.IsNullOrEmpty(minBackMoneyRatio) ? "" : (minBackMoneyRatio.Split(',').FirstOrDefault(pp => pp.StartsWith(p.Value.ID.ToString())) ?? "_").Split('_')[1];
                list.Add(bmrm);
            });
            return list;
        }
    }

    /// <summary>
    /// 不同奖金模式的返点配置
    /// </summary>
    public class BackMoneyRatioModel
    {
        public Option_Site_Key key { get; set; }
        /// <summary>
        /// 奖金模式ID
        /// </summary>
        public int WinModelID { get; set; }
        /// <summary>
        /// 值
        /// </summary>
        public string Value { get; set; }
    }
}

